package com.example.rabbitmq_server.file;

/**
 * @author yifs
 * @version 1.0
 * @date 2024/3/28 9:21
 */

import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextField;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.ResourceBundle;

public class DownloadController implements Initializable {

    @FXML
    private TextField urlTextField;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        // No initialization needed here for the TextField as it's already bound in FXML.
    }

    @FXML
    private void downloadFile() {
        String urlString = urlTextField.getText();
        try {
            URL url = new URL(urlString);
            URLConnection connection = url.openConnection();
            connection.connect();

            String fileName = url.getFile();
            if (fileName.contains("/")) {
                fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
            }

            InputStream input = connection.getInputStream();
            File outputFile = new File(fileName);
            try (OutputStream output = new FileOutputStream(outputFile)) {
                byte[] buffer = new byte[1024];
                int length;
                while ((length = input.read(buffer)) > 0) {
                    output.write(buffer, 0, length);
                }
                System.out.println("文件已成功下载到：" + outputFile.getAbsolutePath());
            } catch (Exception e) {
                System.out.println("下载文件时发生错误: " + e.getMessage());
            } finally {
                input.close();
            }
        } catch (Exception e) {
            System.out.println("打开URL或连接到服务器时发生错误: " + e.getMessage());
        }
    }

    private String getFileNameFromUrl(URL url) {
        String fileName = url.getFile();
        return fileName.substring(fileName.lastIndexOf('/') + 1);
    }
}
